<?php defined('SYSPATH') or die('No direct script access.');

class Helper_Index
{
    public static function model_info(Model_Model $model, Model_Price $price = null)
    {
        $content = new View('index/model/_info_tpl');
        $content->model = $model;
        $content->price = $price;
        return $content;    
    }
    
    public static function new_model_info($model)
    {
        $content = new View('index/model/_new_info_tpl');
        $content->model = $model;
        return $content;    
    }
    
    public static function reviews_score($model)
    {
        $class = null;
        foreach (ORM::factory('model')->get_available_scores() as $score => $item) {
            if ($model->score >= $item['from'] &&
                $model->score <= $item['to']) {
                $class = 'score'.$score;
                break;    
            }    
        }
        
        return '<div class="score '.$class.'">'.$model->score.'</div>';    
    }
    
    public static function score_name($model)
    {
        $name = null;
        foreach (ORM::factory('model')->get_available_scores() as $score => $item) {
            if ($model->score >= $item['from'] &&
                $model->score <= $item['to']) {
                $name = $item['name'];
                break;    
            }    
        }
        
        return $name;
    }
    
    public static function review_source($review)
    {
        $sources = array(
            'yandexmarket' => 'Маркет.Яндекс',
            'irecommend'   => 'IRecommend.ru',
        );
        
        if (isset($sources[$review['entity']])) {
            return $sources[$review['entity']];
        }
        return null;   
    }
    
    public static function reviews($reviews)
    {
        $content = new View('index/model/_reviews_tpl');
        $content->reviews = $reviews;
        return $content;    
    }
    
    public static function reviews_details($model)
    {
        $content = new View('index/model/_reviews_details_tpl');
        $content->model = $model;
        return $content;    
    }
    
    public static function big_rating($model)
    {
        $content = new View('index/model/_big_rating_tpl');
        $content->model = $model;
        return $content;    
    }
    
    public static function products_list($products, $coupons = null)
    {
        $content = new View('index/product/_products_list_tpl');
        $content->products = $products;
        $content->coupons  = $coupons;
        return $content;        
    }
    
    public static function sidebar_products_list($products, $coupons = null)
    {
        $content = new View('index/product/_sidebar_products_list_tpl');
        $content->products = $products;
        $content->coupons  = $coupons;
        return $content;        
    }
    
    public static function new_navigation($model, $current = '')
    {
        $menu = array(
            ''             => 'Обзор',
            '/competitors' => 'Конкуренты',
            '/specs'       => 'Характеристики',
            '/reviews'     => 'Отзывы',
        ); 
        
        $content = new View('index/model/new/_navigation_tpl');
        $content->model   = $model;
        $content->menu    = $menu;
        $content->current = $current;
        return $content;   
    }
    
    public static function go_product_url($product) {
        return '/product/go/'.$product->id;
    }
    
    public static function go_coupon_url($coupon, $product) {
        return '/coupon/go/'.$coupon->id.'/'.$product->id;
    }
    
    public static function product_url($product) {
        return '/product/'.$product->id.'-'.Model_Main::translit($product->name);
    }
    
    public static function category_url($category, $brand = null, $append_query = false) {
        if ($category instanceof Model_Category) {
            $url = '/category/'.$category->id.'-'.Model_Main::translit($category->name); 
        } else {
            $url = '/category/'.$category['id'].'-'.Model_Main::translit($category['name']);   
        }
        if ($brand) {
            if ($brand instanceof Model_Brand) {
                $url .= '/brand/'.$brand->id.'-'.Model_Main::translit($brand->name);    
            } else {
                $url .= '/brand/'.$brand['id'].'-'.Model_Main::translit($brand['name']);    
            }
               
        }
        if ($append_query && $_SERVER['QUERY_STRING']) {
            $url .= '?'.$_SERVER['QUERY_STRING'];    
        }
        return $url;
    }
    
    public static function models_search_list($models)
    {
        $content = new View('index/model/_search_list_tpl');
        $content->models = $models;
        return $content;    
    }
    
    public static function date($date)
    {
        $d = date('d', $date);
        $m = date('m', $date);
        $y = date('Y', $date);
        
        $months = array(
            '01' => 'января',
            '02' => 'февраля',
            '03' => 'марта',
            '04' => 'апреля',
            '05' => 'мая',
            '06' => 'июня',
            '07' => 'июля',
            '08' => 'августа',
            '09' => 'сентября',
            '10' => 'октября',
            '11' => 'ноября',
            '12' => 'декабря',
        );
        
        return $d . ' ' . $months[$m] . ' ' . $y;
    }
    
    public static function get_medium_share_buttons()
    {
        $code = <<<CODE
<script type="text/javascript">(function() {
  if (window.pluso) if (typeof window.pluso.start == "function") return;
  var d = document, s = d.createElement('script'), g = 'getElementsByTagName';
  s.type = 'text/javascript'; s.charset='UTF-8'; s.async = true;
  s.src = ('https:' == window.location.protocol ? 'https' : 'http')  + '://share.pluso.ru/pluso-like.js';
  var h=d[g]('head')[0] || d[g]('body')[0];
  h.appendChild(s);
})()
</script>
<div data-user="1705339630" class="pluso" data-background="none;" data-options="medium,square,line,horizontal,counter,sepcounter=1,theme=14" data-services="vkontakte,odnoklassniki,facebook,twitter,google,moimir,email"></div>
CODE;
        return '<div class="medium-social-buttons">'.$code.'</div>';
    }
    
    public static function get_big_share_buttons()
    {
        $code = <<<CODE
<script type="text/javascript">(function() {
  if (window.pluso) if (typeof window.pluso.start == "function") return;
  var d = document, s = d.createElement('script'), g = 'getElementsByTagName';
  s.type = 'text/javascript'; s.charset='UTF-8'; s.async = true;
  s.src = ('https:' == window.location.protocol ? 'https' : 'http')  + '://share.pluso.ru/pluso-like.js';
  var h=d[g]('head')[0] || d[g]('body')[0];
  h.appendChild(s);
})()
</script>
<div data-user="1705339630" class="pluso" data-background="none;" data-options="big,square,line,horizontal,counter,sepcounter=1,theme=14" data-services="vkontakte,odnoklassniki,facebook,twitter,google,moimir,email"></div>
CODE;
        return '<div class="big-social-buttons"><span>Понравилась страничка? Расскажите о ней своим друзьям!</span><div class="buttons">'.$code.'</div></div>';   
    }
    
    public static function get_comments()
    {
        $app_id = 3850381;
        if (!Model_Main::is_production_host()) {
            $app_id = 3850384;    
        }
        
        $code = <<<CODE
<script type="text/javascript">
  VK.init({apiId: {$app_id}, onlyWidgets: true});
</script>

<!-- Put this div tag to the place, where the Comments block will be -->
<div id="vk_comments"></div>
<script type="text/javascript">
VK.Widgets.Comments("vk_comments", {limit: 20, width: "1000", attach: "*"});
</script>   
CODE;
        return $code;
    }
    
    public static function pagination($page, $per_page, $count, $url, $first_url, $sort = null, $params = null)
    {
        if (ceil($count / $per_page) <= 1) {
            return '';
        }
        $content = new View('index/_pagination_tpl');
        $content->page     = $page;
        $content->per_page = $per_page;
        $content->count    = $count;
        $content->url      = $url;
        $content->first_url = $first_url;
        $content->sort     = $sort;
        if ($params) {
            $empty = true;
            foreach ($params as &$param) {
                if (is_null($param)) {
                    $param = '';    
                } else {
                    $empty = false;    
                }   
            }
            if ($empty) {
                $params = null;    
            }
        }
        $content->params   = $params;
        return $content;   
    }
    
    public static function anchor_text($text)
    {
        $n = mt_rand(0, 2);
        if ($n == 0) {
            return $text . ' отзывы';
        } else if ($n == 1) {
            return 'Отзывы о ' . $text;
        }
        return $text;
    } 
    
    public static function top_menu()
    {
        $content = new View('index/_top_menu_tpl');
        $content->categories = ORM::factory('category')->get_categories_tree();
        return $content;   
    }
    
    public static function format_int($value)
    {
        return number_format((int)$value, 0, '', ' ');
    }
    
    /**
    *  Множественное число
    *
    * @param int $howmuch
    * @param array $input Например: [0] - комментарий, [1] - комментария, [2] - комментариев
    * @return string
    */
    public static function plural_form($howmuch, array $input) {
        $howmuch = (int)$howmuch;
        $l2 = substr($howmuch,-2);
        $l1 = substr($howmuch,-1);
        if($l2 > 10 && $l2 < 20) return $input[2];
        else
        switch ($l1) {
            case 0: return $input[2]; break;
            case 1: return $input[0]; break;
            case 2: case 3: case 4: return $input[1]; break;
            default: return $input[2]; break;
        }
        return false;
    }
    
    public static function get_product_index_description($product)
    {
        return 'Купите '.$product->name.' за '.$product->price.' руб. Возможны выгодные скидки!';
    }
    
    public static function get_category_index_description($category, $brand = null)
    {
        $text = $category->name;
        if ($brand) {
            $text .= ' '.$brand->name;    
        }
        $text .= '. Огромный выбор товаров изо всех магазинов одежды и обуви. Вы подберете себе красивую и нужную вещь';
        return $text;
    }
    
    public static function get_product_index_text($product, $category)
    {
        $text = '<p>У нас вы сможете купить '.$product->name.' за '.$product->price.' рублей. В колонке справа мы постарались подобрать товары, которые также должны вам понравиться.</p>'.
        '<p>Возможно скорое появление скидок на <a href="'.self::category_url($category).'">'.mb_strtolower($category->name).'</a>';
        if ($product->brand_id) {
            $brand = ORM::factory('brand', $product->brand_id);
            $text .= ' или <a href="'.self::category_url($category, $brand).'">'.mb_strtolower($category->name).' '.$brand->name.'</a>';    
        }
        $text .= ', так что не пропустите.</p>';
        return $text;
    } 
    
    public static function get_category_index_text($category, $brand)
    {
        $text = 'Купите '.mb_strtolower($category->name);
        if ($brand) {
            $text .= ' '.$brand->name;        
        }
        $text .= ' в нашем интернет-магазине.';
        return $text;
    } 
} 
